package com.xigua.chapterTow;

import com.sun.org.apache.bcel.internal.generic.NEW;

import java.util.Random;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: 原则一 微基准测试
 * @date 2022/1/822:11
 */
public class FibonacciTest {
    private volatile double l;
    private int nLoops;
    private int[] input;

    public static void main(String[] args) {
        FibonacciTest f = new FibonacciTest(5);
        f.doTest(true);
        f.doTest(false);
    }

    private FibonacciTest(int nLoops){
        this.nLoops = nLoops;
        input = new int[nLoops];
        Random r = new Random();
        for (int i = 0; i < this.nLoops; i++) {
            input[i] = r.nextInt();
        }
    }


    private void doTest(boolean isWarmup){
        long then = System.currentTimeMillis();
        for (int i = 0; i < nLoops; i++) {
            l = fibIml1(input[i]);
        }
        if (!isWarmup){
            long now = System.currentTimeMillis();
            System.out.println("Elapsed time:"+(now - then));
        }

    }

    private double fibIml1(int n){
        if (n < 0) throw  new IllegalArgumentException("must be > 0");
        if (n <=1) return n;
        double d = fibIml1(n-1)+fibIml1(n-2);
        if (Double.isInfinite(d)) throw new ArithmeticException("Overflow");
        return d;

    }
}
